package com.bear.richtext.type

import android.content.Context
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import com.bear.richtext.R
import com.bear.richtext.utils.Tools
import org.json.JSONObject

/**
 * 图片组件
 */
class ItemImage() : RichItem() {
    companion object {
        val IMAGE_PATH = "imagePath"
    }

    private var imagePath = ""

    override fun toJson(): JSONObject {
        (this.richView as FrameLayout)?.let {
            var jsonObject = JSONObject()
            jsonObject.put(TYPE, RichItemType.Image)
            var attrs = JSONObject()
            attrs.put(IMAGE_PATH, imagePath)
            jsonObject.put(ATTRS, attrs)
            return jsonObject
        }
        return JSONObject()
    }

    override fun parse(context: Context, jsonObject: JSONObject): FrameLayout {
        try {
            imagePath = jsonObject.optJSONObject(ATTRS).optString(IMAGE_PATH, imagePath)
        } catch (e: Exception) {

        }
        val imageLayout =
            LayoutInflater.from(context).inflate(R.layout.edit_imageview, null) as FrameLayout
        this.richView = imageLayout
        val imageView = imageLayout.findViewById<ImageView>(R.id.edit_imageView)
        Tools.getImgLoad().loadImg(context, imagePath, imageView!!)
        return imageLayout
    }

    constructor(context: Context, imagePath: String?) : this() {
        imagePath?.let {
            this.imagePath = imagePath
        }
        this.richView = parse(context, JSONObject())
    }

    constructor(context: Context, jsonObject: JSONObject) : this() {
        this.richView = parse(context, jsonObject)
    }

    override fun type(): RichItemType {
        return RichItemType.Image
    }
}